package com.xinxing.learning.security.filter;

import com.xinxing.learning.security.exception.CaptchaNotMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 扩展验证码登录filter
 */
public class CaptchaFilter extends UsernamePasswordAuthenticationFilter {

    private static final String SPRING_SECURITY_FORM_CAPTCHA_KEY = "captcha";

    private String captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String verifyCode = request.getParameter(this.getCaptchaParameter());
        String sessionVerifyCode = (String) request.getSession().getAttribute("captcha");
        if (Objects.nonNull(verifyCode)
                && Objects.nonNull(sessionVerifyCode)
                && verifyCode.equalsIgnoreCase(sessionVerifyCode)) {
            return super.attemptAuthentication(request, response);
        }

        throw new CaptchaNotMatchException("验证码不匹配!");
    }

    public String getCaptchaParameter() {
        return captchaParameter;
    }

    public void setCaptchaParameter(String captchaParameter) {
        this.captchaParameter = captchaParameter;
    }
}
